package aqua.smile.springboot.rediscache.services;

import cn.hutool.core.map.MapBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class RedisCacheDemoService {

    @Caching(cacheable = {
            @Cacheable(cacheNames = "demoCache", key = "#id"),
            @Cacheable(cacheNames = "demoCache2", key = "#id"),
            @Cacheable(cacheNames = "demo3", key = "#id")
    })
    public Object getUserById(Integer id) {
        log.info("数据库查询....");
        return MapBuilder.create()
                .put("id", id)
                .put("name", "user" + id)
                .build();
    }

    @Cacheable(cacheNames = "user", key = "#phone")
    public User getUserByPhone(String phone) {
        log.info("执行getUserByPhone...");
        return new User()
                .setUserId(1001)
                .setPhone(phone)
                .setName("from Get")
                ;
    }

    @CachePut(cacheNames = "user", key = "#phone")
    public User updateUserByPhone(String phone) {
        log.info("执行updateUserByPhone...");
        return new User()
                .setUserId(1001)
                .setPhone(phone)
                .setName("from Update")
                ;
    }

    /**
     * #result 从返回值中取值
     *
     * @param phone
     * @return
     */
    @CachePut(cacheNames = "user", key = "#result.phone")
    public User updateUserByPhone2(String phone) {
        log.info("执行updateUserByPhone2...");
        return new User()
                .setUserId(1001)
                .setPhone(phone)
                .setName("from Update 2")
                ;
    }

    @CacheEvict(cacheNames = "user", key = "#phone")
    public void removeUserByPhone(String phone) {
        log.info("执行removeUserByPhone...");
    }

}
